package com.circle.rest.core.jwt;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.circle.rest.core.util.RedisUtil;
import com.circle.rest.core.util.ToolUtil;
import com.circle.rest.modular.sys.model.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    static final String SECRET = "rest2019";

    /**
     * 生成token
     *
     * @param user
     * @return
     */
    public static String generateToken(User user) {
        HashMap<String, Object> map = new HashMap<>();
        //you can put any data in the map
        String jsonString = JSON.toJSONString(user);
        map.put("user", jsonString);
        String token = Jwts.builder()
                .setClaims(map)
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 7L))//7天过期
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
        RedisUtil.set("JWT-TOKEN:" + user.getId(), token, 60 * 60 * 24 * 7L);
        return token;
    }

    /**
     * 校验token
     *
     * @param token
     * @return
     */
    public static Map<String, Object> validateToken(String token) {
        // parse the token.
        Map<String, Object> body = Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token.replace("Bearer ", ""))
                .getBody();
        return body;
    }

    /**
     * 获取登录用户信息
     *
     * @param request
     * @return
     */
    public static User getUser(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (ToolUtil.isEmpty(token)) {
            return null;
        }
        Map<String, Object> map = validateToken(token.replace("Bearer ", ""));
        String json = map.get("user").toString();
        User user = JSONObject.parseObject(json, User.class);
        return user;
    }

    /**
     * token过期时间（秒）
     *
     * @return
     */
    public static Long getExpiration() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("Authorization");
        if (ToolUtil.isEmpty(token)) {
            return null;
        }
        Claims claims = Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token.replace("Bearer ", ""))
                .getBody();
        Date expiration = claims.getExpiration();
        long now = System.currentTimeMillis();
        long time = expiration.getTime();
        return time - now;
    }
}